package net.ebakker.tvseries.reader;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.ebakker.tvseries.main.Pair;

public final class TorrentNameParser {

	private TorrentNameParser() {
		// avoid instantiation.
	}

	public static Pair<String, Integer> parseTorrent(String torrent) {
		Pattern pattern = Pattern.compile("(.*)\\.S(\\d\\d)E.*");
		Matcher matcher = pattern.matcher(torrent);

		Pattern britishPattern = Pattern.compile("(.*)\\.(\\d{1,2})x.*");
		Matcher britishMatcher = britishPattern.matcher(torrent);

		String seriesName = "";
		int seriesSeason = 0;

		if (matcher.find()) {
			seriesName = parseName(matcher.group(1));
			seriesSeason = fixAmericanDad(seriesName, Integer.parseInt(matcher.group(2)));
		} else if (britishMatcher.find()) {
			seriesName = parseName(britishMatcher.group(1));
			seriesSeason = Integer.parseInt(britishMatcher.group(2));
		}

		return new Pair<>(seriesName, Integer.valueOf(seriesSeason));
	}

	private static int fixAmericanDad(String seriesName, int season) {
		if ("American Dad".equals(seriesName)) {
			return season + 1;
		}
		return season;
	}

	private static String parseName(String group) {
		return group.replaceAll("\\.|_", " ").trim();
	}

}
